<?php

// 浏览器友好的变量输出
function dump($var, $echo=true, $label=null, $strict=true) {
    return MDebug::dump($var, $echo, $label, $strict);
}

/**
 * (功能描述) 取得请求的 URI 信息（不含协议、主机名）
 *
 * 例如： http://mphp.com/admin/index.php?controller=test
 * 返回： /admin/index.php?controller=test
 *
 * @return string
 */
function get_request_uri()
{
    static $request_uri = null;
    if (!is_null($request_uri)) return $request_uri;

    if (isset($_SERVER['HTTP_X_REWRITE_URL']))
    {
        $request_uri = $_SERVER['HTTP_X_REWRITE_URL'];
    }
    elseif (isset($_SERVER['REQUEST_URI']))
    {
        $request_uri = $_SERVER['REQUEST_URI'];
    }
    elseif (isset($_SERVER['ORIG_PATH_INFO']))
    {
        $request_uri = $_SERVER['ORIG_PATH_INFO'];
        if (!empty($_SERVER['QUERY_STRING']))
        {
            $request_uri .= '?' . $_SERVER['QUERY_STRING'];
        }
    }
    else
    {
        $request_uri = '';
    }

    return $request_uri;
}

/**
 * (功能描述) 取得请求的 URI 信息（不含协议、主机名、查询参数、PATHINFO）
 *
 * 例如：
 * http://mphp.com/admin/index.php?controller=test
 * http://mphp.com/admin/index.php/path/to
 * 都返回： /admin/index.php
 *
 * @return string
 */
function get_request_baseuri()
{
    static $request_base_uri = null;
    if (!is_null($request_base_uri)) return $request_base_uri;

    $uri = get_request_uri();
    $pos = strpos($uri, '?');
    {
        $uri = substr($uri, 0, $pos);
    }
    $pathinfo = get_request_pathinfo();
    $len = strlen($pathinfo);
    if ($len)
    {
        $uri = rtrim($uri, '/');
        if (substr($uri, -$len) == $pathinfo)
        {
            $uri = substr($uri, 0, -$len);
        }
    }
    $request_base_uri = $uri;
    return $uri;
}

/**
 * (功能描述) 取得响应请求的 .php 文件在 URL 中的目录部分
 *
 * 例如： http://mphp.com/admin/index.php?controller=test
 * 返回： /admin/
 *
 * @return string
 */
function get_request_dir()
{
    static $dir = null;
    if (!is_null($dir)) return $dir;

    $dir = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/\\') . '/';
    return $dir;
}

/**
 * (功能描述) 返回 PATHINFO 信息
 *
 * 例如：http://mphp.com/admin/index.php/path/to
 * 返回： /path/to
 *
 * @return string
 */
function get_request_pathinfo()
{
    static $pathinfo = null;
    if (!is_null($pathinfo)) return $pathinfo;

    $pathinfo = get_request_uri();
    $pos = strpos($pathinfo, '?');
    if ($pos !== false)
    {
        $pathinfo = substr($pathinfo, 0, $pos);
    }
    $pathinfo = (string)substr($pathinfo, strlen($_SERVER['SCRIPT_NAME']));
    $pathinfo = rtrim($pathinfo, '/');
    return $pathinfo;
}

function is_post()
{
    return $_SERVER['REQUEST_METHOD'] == 'POST';
}

function is_ajax()
{
    return strtolower(get_http_header('X_REQUESTED_WITH')) == 'xmlhttprequest';
}

// 去除代码中的空白和注释
function strip_whitespace($content) {
    $stripStr = '';
    //分析php源码
    $tokens = token_get_all($content);
    $last_space = false;
    for ($i = 0, $j = count($tokens); $i < $j; $i++) {
        if (is_string($tokens[$i])) {
            $last_space = false;
            $stripStr .= $tokens[$i];
        } else {
            switch ($tokens[$i][0]) {
                //过滤各种PHP注释
                case T_COMMENT:
                case T_DOC_COMMENT:
                    break;
                //过滤空格
                case T_WHITESPACE:
                    if (!$last_space) {
                        $stripStr .= ' ';
                        $last_space = true;
                    }
                    break;
                case T_START_HEREDOC:
                    $stripStr .= "<<<THINK\n";
                    break;
                case T_END_HEREDOC:
                    $stripStr .= "THINK;\n";
                    for($k = $i+1; $k < $j; $k++) {
                        if(is_string($tokens[$k]) && $tokens[$k] == ';') {
                            $i = $k;
                            break;
                        } else if($tokens[$k][0] == T_CLOSE_TAG) {
                            break;
                        }
                    }
                    break;
                default:
                    $last_space = false;
                    $stripStr .= $tokens[$i][1];
            }
        }
    }
    return $stripStr;
}

// 循环创建目录
function mk_dir($dir, $mode = 0777) {
    if (is_dir($dir) || @mkdir($dir, $mode))
        return true;
    if (!mk_dir(dirname($dir), $mode))
        return false;
    return @mkdir($dir, $mode);
}

// xml编码
function xml_encode($data, $encoding='utf-8', $root='think') {
    $xml = '<?xml version="1.0" encoding="' . $encoding . '"?>';
    $xml.= '<' . $root . '>';
    $xml.= data_to_xml($data);
    $xml.= '</' . $root . '>';
    return $xml;
}

function data_to_xml($data) {
    $xml = '';
    foreach ($data as $key => $val) {
        is_numeric($key) && $key = "item id=\"$key\"";
        $xml.="<$key>";
        $xml.= ( is_array($val) || is_object($val)) ? data_to_xml($val) : $val;
        list($key, ) = explode(' ', $key);
        $xml.="</$key>";
    }
    return $xml;
}

// 获取客户端IP地址
function get_client_ip() {
    static $ip = NULL;
    if ($ip !== NULL) return $ip;
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $pos =  array_search('unknown',$arr);
        if(false !== $pos) unset($arr[$pos]);
        $ip   =  trim($arr[0]);
    }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    }elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $ip = (false !== ip2long($ip)) ? $ip : '0.0.0.0';
    return $ip;
}

function send_http_status($code) {
    static $_status = array(
        // Success 2xx
        200 => 'OK',
        // Redirection 3xx
        301 => 'Moved Permanently',
        302 => 'Moved Temporarily ',  // 1.1
        // Client Error 4xx
        400 => 'Bad Request',
        403 => 'Forbidden',
        404 => 'Not Found',
        // Server Error 5xx
        500 => 'Internal Server Error',
        503 => 'Service Unavailable',
    );
    if(isset($_status[$code])) {
        header('HTTP/1.1 '.$code.' '.$_status[$code]);
        // 确保FastCGI模式下正常
        header('Status:'.$code.' '.$_status[$code]);
    }
}


?>